package com.way.activity;

import javax.crypto.SecretKey;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.zxing.CaptureActivity;
import com.way.app.App;
import com.way.qrcode.R;
import com.way.util.DesEncrypt;
import com.way.util.T;

public class MainActivity extends SherlockFragmentActivity {
	static final private int GET_CODE = 0;
	private App mApp;
	private ImageView createQR;
	private ImageView scanQR;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_qrcode);
		mApp = App.getApp();
		init();
		addListeners();

	}

	private void addListeners() {

		createQR.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						CreateQRActivity.class);
				startActivity(intent);
			}
		});
		scanQR.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						CaptureActivity.class);
				startActivityForResult(intent, GET_CODE);
			}
		});
	}

	private void init() {

		createQR = (ImageView) findViewById(R.id.createQRCode);
		scanQR = (ImageView) findViewById(R.id.scanQRCode);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 当前只有一个返回值
		if (resultCode == RESULT_OK && requestCode == GET_CODE) {
			String result = data.getExtras().getString("result");
			if (TextUtils.isEmpty(result)) {
				Toast.makeText(this, R.string.scan_retry, Toast.LENGTH_LONG)
						.show();
				return;
			}
			SecretKey key = mApp.getSecretKey();
			if (key == null) {
				Toast.makeText(this, "密钥不存在，无法解析二维码", Toast.LENGTH_LONG).show();
				return;
			}
			String desResult = DesEncrypt.getDesString(result, key);
			if (!TextUtils.isEmpty(desResult)) {
				Log.i("way", "解析后：" + DesEncrypt.getDesString(result, key));
				Toast.makeText(this, DesEncrypt.getDesString(result, key),
						Toast.LENGTH_LONG).show();
			} else {
				Log.i("way", "解析后：" + result);
				Toast.makeText(this, result, Toast.LENGTH_LONG).show();
			}

		}
	}

	/**
	 * 连续按两次返回键就退出
	 */
	private long firstTime;

	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() - firstTime < 3000) {
			finish();
		} else {
			firstTime = System.currentTimeMillis();
			T.showShort(this, R.string.press_again_exit);
		}
	}

}
